package com.onlyxiahui.framework.action.dispatcher.registry;

import java.util.LinkedList;
import java.util.List;

import org.springframework.core.MethodParameter;

import com.onlyxiahui.framework.action.dispatcher.ActionContext;
import com.onlyxiahui.framework.action.dispatcher.extend.ActionRequest;
import com.onlyxiahui.framework.action.dispatcher.extend.ActionResponse;
import com.onlyxiahui.framework.action.dispatcher.extend.ArgumentBox;
import com.onlyxiahui.framework.action.dispatcher.extend.MethodArgumentResolver;

/**
 * Date 2019-01-12 09:18:11<br>
 * Description
 * 
 * @author XiaHui<br>
 * @since 1.0.0
 */

public class MethodArgumentResolverRegistry {

	List<MethodArgumentResolver> list = new LinkedList<>();

	public void add(MethodArgumentResolver mar) {
		list.add(mar);
	}

	public boolean supportsParameter(MethodParameter parameter) {
		return (getArgumentResolver(parameter) != null);
	}

	public Object resolveArgument(ActionContext actionContext, MethodParameter parameter, ActionRequest request, ActionResponse response, ArgumentBox argumentBox) {
		MethodArgumentResolver resolver = getArgumentResolver(parameter);
		if (resolver == null) {
			throw new IllegalArgumentException("Unknown parameter type [" + parameter.getParameterType().getName() + "]");
		}
		return resolver.resolveArgument(actionContext, parameter, request, response, argumentBox);
	}

	private MethodArgumentResolver getArgumentResolver(MethodParameter parameter) {
		MethodArgumentResolver result = null;
		for (MethodArgumentResolver methodArgumentResolver : this.list) {
			if (methodArgumentResolver.supportsParameter(parameter)) {
				result = methodArgumentResolver;
				break;
			}
		}
		return result;
	}
}
